/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Biblioteca;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.Properties;

/**
 * ConexaoSSH
 * 
 * Versao 1.0
 * 
 * Data Criação 24/02/2014
 *
 * @author Igor
 */
public abstract class ConexaoSSH {
    
    /**
     * Realiza criacao do tunel SSH para permitir conexao com o Banco de Dados
     * @param strSshUser //Usuario remoto SSH
     * @param strSshPassword //Login remoto SSH
     * @param strSshHost //Hostname remoto SSH
     * @param nSshPort //Porta remota SSH
     * @param strDBRemoteHost //Hostname remoto do Banco de Dados 
     * @param nDBRemotePort //Porta remota Banco de Dados
     * @throws JSchException 
     */
    public static int doSshTunnel(String strSshUser, String strSshPassword, String strSshHost, int nSshPort, String strDBRemoteHost, int nDBRemotePort) throws JSchException, IOException {
        final JSch jsch = new JSch();
        int nLocalPort; //Porta local para vincular SSH
        
        Session session = jsch.getSession(strSshUser, strSshHost, nSshPort);
        session.setPassword(strSshPassword);

        final Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        
        //Pegando porta local
        ServerSocket s = new ServerSocket(0);
        nLocalPort =  s.getLocalPort();
        s.close();
        //**

        session.connect();
        session.setPortForwardingL(nLocalPort, strDBRemoteHost, nDBRemotePort);
        
        return nLocalPort;
    }
}
